<template>
  <el-cascader
    style="width: 100%"
    v-model="selected"
    :placeholder="placeholder"
    @change="select"
    :options="dataList"
    :props="config"
    clearable
    filterable
  ></el-cascader>
</template>

<script setup lang="ts" name="selectFilter">
import { computed, onMounted, ref } from "vue";
import { getCascadeValue } from "@/utils";
import { useDataStore } from "@/stores/modules/data";
import { watch } from "vue";

interface SelectFilterProps {
  dataKey: string;
  requestApi?: (params: any) => Promise<any>; // 请求表格数据的 api ==> 非必传
  itemValue: string;
  placeholder?: string;
  config?: {};
}

const props = withDefaults(defineProps<SelectFilterProps>(), {
  placeholder: () => "请选择",
  itemValue: "",
  config: () => ({})
});

const dataStore = useDataStore();
const selected = ref();

const dataList = computed(() => {
  return dataStore.getCommonDataByName(props.dataKey);
});

watch([dataList, () => props.itemValue], () => {
  const selectValue = getCascadeValue(dataList.value, props.itemValue);
  selected.value = selectValue;
});

onMounted(() => {
  dataStore.findList(props.dataKey, props.requestApi);
  if (dataList.value) {
    const selectValue = getCascadeValue(dataList.value, props.itemValue);
    selected.value = selectValue;
  }
});

const select = () => {
  if (selected.value && selected.value.length > 0) {
    emit("update:itemValue", selected.value[selected.value.length - 1]);
    emit("change", selected.value[selected.value.length - 1]);
  } else {
    emit("update:itemValue", "");
    emit("change", "");
  }
};

// emit
const emit = defineEmits<{
  "update:itemValue": [value: any];
  change: [value: any];
}>();
</script>

<style scoped lang="scss"></style>
